/**
 * @param {number[][]} grid
 * @return {number}
 */
var orangesRotting = function (grid) {
  const m = grid.length,
    n = grid[0].length;
  const arr = [];
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === 2) {
        arr.push([i, j]);
      }
    }
  }
  let target = -1;
  while (arr.length !== 0) {
    const len = arr.length;
    target++;
    // console.log(grid);
    for (let i = 0; i < len; i++) {
      const orange = arr.shift();
      const x = orange[0],
        y = orange[1];
      if (x > 0 && grid[x - 1][y] === 1) {
        arr.push([x - 1, y]);
        grid[x - 1][y] = 2;
      }
      if (x < m - 1 && grid[x + 1][y] === 1) {
        arr.push([x + 1, y]);
        grid[x + 1][y] = 2;
      }
      if (y > 0 && grid[x][y - 1] === 1) {
        arr.push([x, y - 1]);
        grid[x][y - 1] = 2;
      }
      if (y < n - 1 && grid[x][y + 1] === 1) {
        arr.push([x, y + 1]);
        grid[x][y + 1] = 2;
      }
    }
  }
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === 1) {
        return -1;
      }
    }
  }
  return target === -1 ? 0 : target;
};
// 示例测试
const grid = [
  [2, 2],
  [1, 1],
  [0, 0],
  [2, 0],
];
console.log(orangesRotting(grid));
